package com.shirojwt.controller;

import com.shirojwt.com.lang.JwtResultMap;
import com.shirojwt.entity.Account;
import com.shirojwt.service.AccountService;
import com.shirojwt.utils.JwtUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * @author chenguo
 * @date 2021/10/12 4:03 下午
 */
@Controller
public class LoginController {
    @Resource
    private JwtResultMap resultMap;

    @Resource
    private AccountService accountService;

    @PostMapping("/login")
    @ResponseBody
    public JwtResultMap login(String username, String password){
        Account account = accountService.findByUsername(username);
        if(null == account){
            return resultMap.fail().code(401).message("账号错误");
        }else if(!password.equals(account.getPassword())){
            return resultMap.fail().code(401).message("密码错误");
        }
        return resultMap.success().code(200).message(JwtUtil.createToken(username));
    }

    @ResponseBody
    @GetMapping("/unauthorized/{message}")
    public JwtResultMap unauthorized(@PathVariable String message){
        return resultMap.success().code(401).message(message);
    }
}
